#!/bin/bash
#
##############################################################################
#                                                                            #
#                        Pi-Star Auto Upgrade Tool                           #
#                                                                            #
#     Version 1.1, Code, Design and Development by Andy Taylor (MW0MWZ).     #
#                                                                            #
#        Make it simple to upgrade to the current version of Pi-Star.        #
#                                                                            #
##############################################################################
#
if [ "$(id -u)" != "0" ]; then
	echo -e "You need to be root to run this command...\n"
	exit 1
fi

exec 200>/var/lock/pistar-upgrade.lock || exit 1
if ! flock -n 200 ; then
	echo -e "Another instance is already running...\n"
	exit 1
fi

main_function() {
	echo "[INFO] Pi-Star Upgrade process starting..."
	# Get the current Modem
	if [ -f /etc/dstar-radio.mmdvmhost ]; then
		pistarModem=$(awk -F "=" '/Hardware/ {print $2}' /etc/dstar-radio.mmdvmhost)
	elif [ -f /etc/dstar-radio.dstarrepeater ]; then
		pistarModem=$(awk -F "=" '/Hardware/ {print $2}' /etc/dstar-radio.dstarrepeater)
	else
		pistarModem=Unknown
	fi

	# Get the Pi-Star Version Info
	pistarCurVersion=$(awk -F "= " '/Version/ {print $2}' /etc/pistar-release)
	# Get the hardware type, this may be important later (RPi | NanoPi | OdroidXU4)
	pistarHardware=$(awk -F "= " '/Hardware/ {print $2}' /etc/pistar-release)

	# Make the disk writable
	if [ -d /boot/firmware ]; then
		$(mount -o remount,rw / >/dev/null 2>&1 </dev/null ; mount -o remount,rw /boot/firmware >/dev/null 2>&1 </dev/null)
	else
		$(mount -o remount,rw / >/dev/null 2>&1 </dev/null ; mount -o remount,rw /boot >/dev/null 2>&1 </dev/null)
	fi

	echo "[INFO] Detected Pi-Star ${pistarCurVersion} running on ${pistarHardware} hardware, attached to ${pistarModem} modem..."

	case ${pistarCurVersion} in
	3.4.*)
		Message="[!] ERROR: Upgrades are no longer supported on Pi-Star 3.4.x please upgrade to a new image."
	;;
	4.0.*)
		Message="[!] ERROR: Upgrades are no longer supported on Pi-Star 4.0.x please upgrade to a new image."
	;;
	4.1.0)
		sed -i 's/4.1.0/4.1.1/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Fix up issues with missing ralink firmware
		apt-get update && apt-get install --reinstall -y firmware-ralink

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.1..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.1)
		sed -i 's/4.1.1/4.1.2/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Disable the Load/Save RFKill status - it complains on every boot.
		systemctl mask systemd-rfkill.service
		systemctl mask systemd-rfkill.socket
		# Clean up some other broken services
		rm -rf /etc/systemd/system/multi-user.target.wants/exim4.service
		rm -rf /etc/systemd/system/multi-user.target.wants/wifi-country.service
		# Clean out some remaining files
		rm -rf /var/lib/systemd/rfkill/platform-*

		# MobileGPS Gateway Service
		echo '[Unit]' > /lib/systemd/system/mobilegps.service
		echo 'Description=Pi-Star MobileGPS Service' >> /lib/systemd/system/mobilegps.service
		echo 'After=syslog.target network.target' >> /lib/systemd/system/mobilegps.service
		echo '' >> /lib/systemd/system/mobilegps.service
		echo '[Service]' >> /lib/systemd/system/mobilegps.service
		echo 'Type=forking' >> /lib/systemd/system/mobilegps.service
		echo 'ExecStart=/usr/local/sbin/mobilegps.service start' >> /lib/systemd/system/mobilegps.service
		echo 'ExecStop=/usr/local/sbin/mobilegps.service stop' >> /lib/systemd/system/mobilegps.service
		echo 'ExecReload=/usr/local/sbin/mobilegps.service restart' >> /lib/systemd/system/mobilegps.service
		echo '' >> /lib/systemd/system/mobilegps.service
		echo '[Install]' >> /lib/systemd/system/mobilegps.service
		echo 'WantedBy=multi-user.target' >> /lib/systemd/system/mobilegps.service
		
		# Enable the service
		systemctl daemon-reload
		systemctl enable mobilegps.service
		
		# Modify the /boot/config.txt to bring it up to date
		sed -i '/USB Current/d' /boot/config.txt
		sed -i '/max_usb_current/d' /boot/config.txt
		sed -i '/Buster Support/d' /boot/config.txt
		sed -i '/dtoverlay=vc4-fkms-v3d/d' /boot/config.txt
		sed -i 's/pi3-miniuart-bt/miniuart-bt/g' /boot/config.txt
		echo "" >> /boot/config.txt
		echo "[pi4]" >> /boot/config.txt
		echo "# Enable DRM VC4 V3D driver on top of the dispmanx display stack" >> /boot/config.txt
		echo "dtoverlay=vc4-fkms-v3d" >> /boot/config.txt
		echo "max_framebuffers=2" >> /boot/config.txt
		echo "" >> /boot/config.txt
		echo "[all]" >> /boot/config.txt
		echo "#dtoverlay=vc4-fkms-v3d" >> /boot/config.txt

		# Remove the exim4 stuff from fstab
		sed -i '/exim4/d' /etc/fstab

		# Add Captive Portal enhancement
		echo "address=/www.msftconnecttest.com/192.168.50.1" >>/etc/dnsmasq.conf
		echo "address=/www.msftncsi.com/192.168.50.1" >>/etc/dnsmasq.conf
		echo "address=/clients3.google.com/192.168.50.1" >>/etc/dnsmasq.conf
		echo "address=/connectivitycheck.gstatic.com/192.168.50.1" >>/etc/dnsmasq.conf
		echo "address=/connectivitycheck.android.com/192.168.50.1" >>/etc/dnsmasq.conf
		echo "address=/www.appleiphonecell.com/192.168.50.1" >>/etc/dnsmasq.conf
		echo "address=/captive.apple.com/192.168.50.1" >>/etc/dnsmasq.conf
		echo "address=/www.apple.com/192.168.50.1" >>/etc/dnsmasq.conf
		echo "address=/.apple.com.edgekey.net/192.168.50.1" >>/etc/dnsmasq.conf

		# Add the Captive Portal to nginx
		echo "server_names_hash_bucket_size 64;" > /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "server {" >> /etc/nginx/sites-available/captive-portal
		echo "	listen 80;" >> /etc/nginx/sites-available/captive-portal
		echo "	server_name www.msftconnecttest.com www.msftncsi.com clients3.google.com;" >> /etc/nginx/sites-available/captive-portal
		echo "	return 302 http://192.168.50.1/index.php;" >> /etc/nginx/sites-available/captive-portal
		echo "}" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "server {" >> /etc/nginx/sites-available/captive-portal
		echo "	listen 80;" >> /etc/nginx/sites-available/captive-portal
		echo "	server_name connectivitycheck.gstatic.com connectivitycheck.android.com;" >> /etc/nginx/sites-available/captive-portal
		echo "	return 302 http://192.168.50.1/index.php;" >> /etc/nginx/sites-available/captive-portal
		echo "}" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "server {" >> /etc/nginx/sites-available/captive-portal
		echo "	listen 80;" >> /etc/nginx/sites-available/captive-portal
		echo "	server_name www.appleiphonecell.com captive.apple.com www.apple.com;" >> /etc/nginx/sites-available/captive-portal
		echo "	return 302 http://192.168.50.1/index.php;" >> /etc/nginx/sites-available/captive-portal
		echo "}" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "server {" >> /etc/nginx/sites-available/captive-portal
		echo "	listen 80;" >> /etc/nginx/sites-available/captive-portal
		echo "	server_name *.apple.com.edgekey.net;" >> /etc/nginx/sites-available/captive-portal
		echo "	return 302 http://192.168.50.1/index.php;" >> /etc/nginx/sites-available/captive-portal
		echo "}" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "server {" >> /etc/nginx/sites-available/captive-portal
		echo "        listen 192.168.50.1:80;" >> /etc/nginx/sites-available/captive-portal
		echo "        root /var/www/dashboard;" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "	try_files \$uri \$uri/ /index.php;" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "        location ^~ /admin {" >> /etc/nginx/sites-available/captive-portal
		echo "		deny	192.168.50.1;" >> /etc/nginx/sites-available/captive-portal
		echo "		allow	192.168.50.0/24;" >> /etc/nginx/sites-available/captive-portal
		echo "		deny	all;" >> /etc/nginx/sites-available/captive-portal
		echo "		try_files \$uri \$uri/ =404;" >> /etc/nginx/sites-available/captive-portal
		echo "		client_max_body_size 512K;" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "	# Load the defaults" >> /etc/nginx/sites-available/captive-portal
		echo "	include             /etc/nginx/default.d/php.conf;" >> /etc/nginx/sites-available/captive-portal
		echo "	}" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "	location ~ /\.git {" >> /etc/nginx/sites-available/captive-portal
		echo "		deny all;" >> /etc/nginx/sites-available/captive-portal
		echo "	}" >> /etc/nginx/sites-available/captive-portal
		echo "" >> /etc/nginx/sites-available/captive-portal
		echo "	# Load the defaults" >> /etc/nginx/sites-available/captive-portal
		echo "	include             /etc/nginx/default.d/*.conf;" >> /etc/nginx/sites-available/captive-portal
		echo "}" >> /etc/nginx/sites-available/captive-portal

		# Link the new site into site-enabled
		cd /etc/nginx/sites-enabled
		ln -s ../sites-available/captive-portal ./
		cd

		# Restart nginx to complete the setup
		systemctl restart nginx

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.2..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.2)
		sed -i 's/4.1.2/4.1.3/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Randomise Daily Cron on boot
		sed -i '/^\/usr\/local\/sbin\/pistar-motdgen/a \\n# Shuffle the time for the daily crontab jobs' /etc/rc.local
		sed -i '/^# Shuffle the time for the daily crontab jobs/a cronMins=$(shuf -i 0-59 -n 1)' /etc/rc.local
		sed -i '/^cronMins=*/a cronHours=$(shuf -i 3-4 -n1)' /etc/rc.local
		sed -i '/^cronHours=*/a mount -o remount,rw \/\nsed -i "/cron.daily/c ${cronMins} ${cronHours}\t* * *\troot\tmount -o remount,rw / && cd / && run-parts --report /etc/cron.daily" /etc/crontab' /etc/rc.local

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.3..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.3)
		sed -i 's/4.1.3/4.1.4/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# APRS Gateway Service
		echo '[Unit]' > /lib/systemd/system/aprsgateway.service
		echo 'Description=Pi-Star APRS Gateway Service' >> /lib/systemd/system/aprsgateway.service
		echo 'After=syslog.target network.target' >> /lib/systemd/system/aprsgateway.service
		echo '' >> /lib/systemd/system/aprsgateway.service
		echo '[Service]' >> /lib/systemd/system/aprsgateway.service
		echo 'Type=forking' >> /lib/systemd/system/aprsgateway.service
		echo 'ExecStart=/usr/local/sbin/aprsgateway.service start' >> /lib/systemd/system/aprsgateway.service
		echo 'ExecStop=/usr/local/sbin/aprsgateway.service stop' >> /lib/systemd/system/aprsgateway.service
		echo 'ExecReload=/usr/local/sbin/aprsgateway.service restart' >> /lib/systemd/system/aprsgateway.service
		echo '' >> /lib/systemd/system/aprsgateway.service
		echo '[Install]' >> /lib/systemd/system/aprsgateway.service
		echo 'WantedBy=multi-user.target' >> /lib/systemd/system/aprsgateway.service

		# APRS Gateway Timer
		echo '[Timer]' > /lib/systemd/system/aprsgateway.timer
		echo 'OnStartupSec=20' >> /lib/systemd/system/aprsgateway.timer
		echo '' >> /lib/systemd/system/aprsgateway.timer
		echo '[Install]' >> /lib/systemd/system/aprsgateway.timer
		echo 'WantedBy=multi-user.target' >> /lib/systemd/system/aprsgateway.timer
		
		# APRS Gateway Config
		echo '[General]' > /etc/aprsgateway
		echo 'Callsign=M1ABC' >> /etc/aprsgateway
		echo 'Debug=0' >> /etc/aprsgateway
		echo 'Daemon=1' >> /etc/aprsgateway
		echo '' >> /etc/aprsgateway
		echo '[APRS-IS]' >> /etc/aprsgateway
		echo 'Server=rotate.aprs2.net' >> /etc/aprsgateway
		echo 'Port=14580' >> /etc/aprsgateway
		echo 'Password=9999' >> /etc/aprsgateway
		echo '' >> /etc/aprsgateway
		echo '[Log]' >> /etc/aprsgateway
		echo 'DisplayLevel=0' >> /etc/aprsgateway
		echo 'FileLevel=1' >> /etc/aprsgateway
		echo 'FilePath=/var/log/pi-star' >> /etc/aprsgateway
		echo 'FileRoot=APRSGateway' >> /etc/aprsgateway
		echo 'FileRotate=1' >> /etc/aprsgateway
		echo '' >> /etc/aprsgateway
		echo '[Network]' >> /etc/aprsgateway
		echo 'Address=127.0.0.1' >> /etc/aprsgateway
		echo 'Port=8673' >> /etc/aprsgateway
		echo '' >> /etc/aprsgateway
		echo '[Enabled]' >> /etc/aprsgateway
		echo 'Enabled=0' >> /etc/aprsgateway

		# Update systemd and enable new services
		systemctl daemon-reload
		systemctl enable aprsgateway.timer

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.4..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.4)
		sed -i 's/4.1.4/4.1.5/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen
		
		# Improved pistar-upnp.service unit file
		echo '[Unit]' > /lib/systemd/system/pistar-upnp.service
		echo 'Description=PiStar-UPnP network service' >> /lib/systemd/system/pistar-upnp.service
		echo 'After=network-online.target ircddbgateway.timer' >> /lib/systemd/system/pistar-upnp.service
		echo 'Wants=network-online.target' >> /lib/systemd/system/pistar-upnp.service
		echo '' >> /lib/systemd/system/pistar-upnp.service
		echo '[Service]' >> /lib/systemd/system/pistar-upnp.service
		echo 'Type=oneshot' >> /lib/systemd/system/pistar-upnp.service
		echo 'RemainAfterExit=true' >> /lib/systemd/system/pistar-upnp.service
		echo 'ExecStart=/usr/local/sbin/pistar-upnp.service start' >> /lib/systemd/system/pistar-upnp.service
		echo 'ExecStopPost=/usr/local/sbin/pistar-upnp.service stop' >> /lib/systemd/system/pistar-upnp.service
		echo '' >> /lib/systemd/system/pistar-upnp.service
		echo '[Install]' >> /lib/systemd/system/pistar-upnp.service
		echo 'WantedBy=multi-user.target' >> /lib/systemd/system/pistar-upnp.service
		
		# Update systemd and enable new services
		systemctl daemon-reload
		if [[ $(systemctl | grep pistar-upnp.timer | wc -l) -gt 0 ]]; then
			systemctl stop pistar-upnp.service
			systemctl start pistar-upnp.service
		fi
		
		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.5..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.5)
		sed -i 's/4.1.5/4.1.6/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Create DGIdGateway Unit files
		echo '[Unit]' > /lib/systemd/system/dgidgateway.service
		echo 'Description=Yaesu System Fusion DGIdGateway Servce' >> /lib/systemd/system/dgidgateway.service
		echo 'After=syslog.target network.target mmdvmhost.timer' >> /lib/systemd/system/dgidgateway.service
		echo '' >> /lib/systemd/system/dgidgateway.service
		echo '[Service]' >> /lib/systemd/system/dgidgateway.service
		echo 'Type=forking' >> /lib/systemd/system/dgidgateway.service
		echo 'ExecStart=/usr/local/sbin/dgidgateway.service start' >> /lib/systemd/system/dgidgateway.service
		echo 'ExecStop=/usr/local/sbin/dgidgateway.service stop' >> /lib/systemd/system/dgidgateway.service
		echo 'ExecReload=/usr/local/sbin/dgidgateway.service restart' >> /lib/systemd/system/dgidgateway.service
		echo '' >> /lib/systemd/system/dgidgateway.service
		echo '[Install]' >> /lib/systemd/system/dgidgateway.service
		echo 'WantedBy=multi-user.target' >> /lib/systemd/system/dgidgateway.service

		echo '[Timer]' > /lib/systemd/system/dgidgateway.timer
		echo 'OnStartupSec=20' >> /lib/systemd/system/dgidgateway.timer
		echo '' >> /lib/systemd/system/dgidgateway.timer
		echo '[Install]' >> /lib/systemd/system/dgidgateway.timer
		echo 'WantedBy=multi-user.target' >> /lib/systemd/system/dgidgateway.timer

		# We are not auto-starting this daemon on purpose, we're not ready for that.
		systemctl daemon-reload

		# Add the DGIdGateway Config
		echo '[General]' > /etc/dgidgateway
		echo 'Callsign=M1ABC' >> /etc/dgidgateway
		echo 'Suffix=ND' >> /etc/dgidgateway
		echo 'Id=1234567' >> /etc/dgidgateway
		echo 'RptAddress=127.0.0.1' >> /etc/dgidgateway
		echo 'RptPort=3200' >> /etc/dgidgateway
		echo 'LocalAddress=127.0.0.1' >> /etc/dgidgateway
		echo 'LocalPort=4200' >> /etc/dgidgateway
		echo 'RFHangTime=20' >> /etc/dgidgateway
		echo 'NetHangTime=20' >> /etc/dgidgateway
		echo 'Bleep=1' >> /etc/dgidgateway
		echo 'Debug=0' >> /etc/dgidgateway
		echo 'Daemon=1' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[Info]' >> /etc/dgidgateway
		echo 'RXFrequency=430000000' >> /etc/dgidgateway
		echo 'TXFrequency=430000000' >> /etc/dgidgateway
		echo 'Power=1' >> /etc/dgidgateway
		echo 'Latitude=50.0' >> /etc/dgidgateway
		echo 'Longitude=-3.0' >> /etc/dgidgateway
		echo 'Height=0' >> /etc/dgidgateway
		echo 'Description=Pi-Star' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[Log]' >> /etc/dgidgateway
		echo 'DisplayLevel=1' >> /etc/dgidgateway
		echo 'FileLevel=1' >> /etc/dgidgateway
		echo 'FilePath=/var/log/pi-star' >> /etc/dgidgateway
		echo 'FileRoot=DGIdGateway' >> /etc/dgidgateway
		echo 'FileRotate=0' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[APRS]' >> /etc/dgidgateway
		echo 'Enable=0' >> /etc/dgidgateway
		echo 'Address=127.0.0.1' >> /etc/dgidgateway
		echo 'Port=8673' >> /etc/dgidgateway
		echo 'Description=APRS Description' >> /etc/dgidgateway
		echo 'Suffix=Y' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[YSF Network]' >> /etc/dgidgateway
		echo 'Hosts=/usr/local/etc/YSFHosts.txt' >> /etc/dgidgateway
		echo 'RFHangTime=20' >> /etc/dgidgateway
		echo 'NetHangTime=20' >> /etc/dgidgateway
		echo 'Debug=0' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[FCS Network]' >> /etc/dgidgateway
		echo 'RFHangTime=20' >> /etc/dgidgateway
		echo 'NetHangTime=20' >> /etc/dgidgateway
		echo 'Debug=0' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[IMRS Network]' >> /etc/dgidgateway
		echo 'RFHangTime=20' >> /etc/dgidgateway
		echo 'NetHangTime=20' >> /etc/dgidgateway
		echo 'Debug=0' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[DGId=0]' >> /etc/dgidgateway
		echo 'Type=Gateway' >> /etc/dgidgateway
		echo 'Static=1' >> /etc/dgidgateway
		echo 'Address=127.0.0.1' >> /etc/dgidgateway
		echo 'Port=42025' >> /etc/dgidgateway
		echo 'Local=42026' >> /etc/dgidgateway
		echo 'RFHangTime=120' >> /etc/dgidgateway
		echo 'NetHangTime=60' >> /etc/dgidgateway
		echo 'Debug=0' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[GPSD]' >> /etc/dgidgateway
		echo 'Enable=0' >> /etc/dgidgateway
		echo 'Address=127.0.0.1' >> /etc/dgidgateway
		echo 'Port=2947' >> /etc/dgidgateway
		echo '' >> /etc/dgidgateway
		echo '[Enabled]' >> /etc/dgidgateway
		echo 'Enabled=0' >> /etc/dgidgateway

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.6..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.6)
		sed -i 's/4.1.6/4.1.7/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 0E98404D386FA1D9
		apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 6ED0E7B82643E131
		apt-get install -y debian-archive-keyring

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.7..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.7)
		sed -i 's/4.1.7/4.1.8/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Create M17Gateway Unit files
		if [[ ! -f /lib/systemd/system/m17gateway.service ]]; then
			echo '[Unit]' > /lib/systemd/system/m17gateway.service
			echo 'Description=M17Gateway Servce' >> /lib/systemd/system/m17gateway.service
			echo 'After=syslog.target network.target mmdvmhost.timer' >> /lib/systemd/system/m17gateway.service
			echo '' >> /lib/systemd/system/m17gateway.service
			echo '[Service]' >> /lib/systemd/system/m17gateway.service
			echo 'Type=forking' >> /lib/systemd/system/m17gateway.service
			echo 'ExecStart=/usr/local/sbin/m17gateway.service start' >> /lib/systemd/system/m17gateway.service
			echo 'ExecStop=/usr/local/sbin/m17gateway.service stop' >> /lib/systemd/system/m17gateway.service
			echo 'ExecReload=/usr/local/sbin/m17gateway.service restart' >> /lib/systemd/system/m17gateway.service
			echo '' >> /lib/systemd/system/m17gateway.service
			echo '[Install]' >> /lib/systemd/system/m17gateway.service
			echo 'WantedBy=multi-user.target' >> /lib/systemd/system/m17gateway.service
		fi

		if [[ ! -f /lib/systemd/system/m17gateway.timer ]]; then
			echo '[Timer]' > /lib/systemd/system/m17gateway.timer
			echo '' >> /lib/systemd/system/m17gateway.timer
			echo 'OnStartupSec=20' >> /lib/systemd/system/m17gateway.timer
			echo '[Install]' >> /lib/systemd/system/m17gateway.timer
			echo 'WantedBy=multi-user.target' >> /lib/systemd/system/m17gateway.timer
		fi

		# Install a basic config
		if [[ ! -f /etc/m17gateway ]]; then
			echo '[General]' > /etc/m17gateway
			echo 'Callsign=M1ABC' >> /etc/m17gateway
			echo 'Suffix=H' >> /etc/m17gateway
			echo 'RptAddress=127.0.0.1' >> /etc/m17gateway
			echo 'RptPort=17011' >> /etc/m17gateway
			echo 'LocalPort=17010' >> /etc/m17gateway
			echo 'Debug=0' >> /etc/m17gateway
			echo 'Daemon=0' >> /etc/m17gateway
			echo '' >> /etc/m17gateway
			echo '[Info]' >> /etc/m17gateway
			echo 'RXFrequency=430475000' >> /etc/m17gateway
			echo 'TXFrequency=439475000' >> /etc/m17gateway
			echo 'Power=1' >> /etc/m17gateway
			echo 'Latitude=0.0' >> /etc/m17gateway
			echo 'Longitude=0.0' >> /etc/m17gateway
			echo 'Height=0' >> /etc/m17gateway
			echo 'Name=Nowhere' >> /etc/m17gateway
			echo 'Description=Multi-Mode Repeater' >> /etc/m17gateway
			echo '' >> /etc/m17gateway
			echo '[Log]' >> /etc/m17gateway
			echo 'DisplayLevel=1' >> /etc/m17gateway
			echo 'FileLevel=1' >> /etc/m17gateway
			echo 'FilePath=/var/log/pi-star' >> /etc/m17gateway
			echo 'FileRoot=M17Gateway' >> /etc/m17gateway
			echo 'FileRotate=1' >> /etc/m17gateway
			echo 'Enabled=1' >> /etc/m17gateway
			echo '' >> /etc/m17gateway
			echo '[Voice]' >> /etc/m17gateway
			echo 'Language=en_GB' >> /etc/m17gateway
			echo 'Directory=/usr/local/etc/M17_Audio' >> /etc/m17gateway
			echo '' >> /etc/m17gateway
			echo '[APRS]' >> /etc/m17gateway
			echo 'Enable=0' >> /etc/m17gateway
			echo 'Address=127.0.0.1' >> /etc/m17gateway
			echo 'Port=8673' >> /etc/m17gateway
			echo 'Suffix=N' >> /etc/m17gateway
			echo 'Description=APRS Description' >> /etc/m17gateway
			echo '' >> /etc/m17gateway
			echo '[Network]' >> /etc/m17gateway
			echo 'Port=17000' >> /etc/m17gateway
			echo 'HostsFile1=/usr/local/etc/M17Hosts.txt' >> /etc/m17gateway
			echo 'HostsFile2=/root/M17Hosts.txt' >> /etc/m17gateway
			echo 'ReloadTime=60' >> /etc/m17gateway
			echo 'Startup=M17-672_E' >> /etc/m17gateway
			echo 'Revert=0' >> /etc/m17gateway
			echo 'HangTime=240' >> /etc/m17gateway
			echo 'Debug=0' >> /etc/m17gateway
			echo '' >> /etc/m17gateway
			echo '[Remote Commands]' >> /etc/m17gateway
			echo 'Enable=1' >> /etc/m17gateway
			echo 'Port=6076' >> /etc/m17gateway
		fi

		# We are not auto-starting this daemon on purpose, we're not ready for that.
		systemctl daemon-reload
		systemctl enable m17gateway.timer

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.8..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.8)
		sed -i 's/4.1.8/4.1.9/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Remove the IPv6 Roadblocks
		rm -rf /etc/modprobe.d/ipv6.conf

		# Clean /etc/sysctl.conf
		sed -i '/net\.ipv6\.conf\.all\.disable_ipv6/d' /etc/sysctl.conf

		# Cleanup apt issues
		rm -rf /etc/apt/sources.list.d/vscode.list
		rm -rf /etc/apt/sources.list.d/stretch-backports.list
		echo 'deb http://archive.debian.org/debian buster-backports main contrib non-free' > /etc/apt/sources.list.d/buster-backports.list

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.9..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.9)
		sed -i 's/4.1.9/4.1.10/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		CONF_FILE="/etc/nginx/sites-available/pi-star"
		if [ ! -f /etc/modprobe.d/ipv6.conf ] && ! grep -q 'listen \[::\]:80 default_server;' "$CONF_FILE" 2>/dev/null; then
			sed -i '/listen 80 default_server;/a\        listen [::]:80 default_server;' "$CONF_FILE"
		fi

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.10..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.1.10)
		#sed -i 's/4.1.10/4.1.11/g' /etc/pistar-release

		# Re-create the MOTD
		#/usr/local/sbin/pistar-motdgen

		# OK we are done
		#Message="[✓] Upgraded from ${pistarCurVersion} to 4.1.11..."
		Message="[✓] You are already running the latest version..."
		#echo $Message
		#exec "$0" "$@"
                #exit 1
	;;
	4.2.0)
		sed -i 's/4.2.0/4.2.1/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Fix Time-Sync issues
		apt-get remove -y --purge ntp ntpdate
		apt-get install -y systemd-timesyncd
		apt-get autoremove -y --purge

		# Clean-up /etc/rc.local
		sed -i '/^# Print the IP address$/,/^fi$/d' /etc/rc.local

		# Remove any pre-existing unit files
		if [ -f /lib/systemd/system/NextionDriver.service ]; then
			rm -rf /lib/systemd/system/NextionDriver.*
		fi
		if [ -f /etc/systemd/system/NextionDriver.service ]; then
			rm -rf /etc/systemd/system/NextionDriver.*
		fi
		if [ -f /etc/systemd/system/nextiondriver.service ]; then
			rm -rf /etc/systemd/system/nextiondriver.*
		fi
		if [ -d /etc/systemd/system/mmdvmhost.service.requires ]; then
			rm -rf /etc/systemd/system/mmdvmhost.service.requires
		fi
		$(sed -i '/Requires=nextiondriver\.service/d' /lib/systemd/system/mmdvmhost.service)

		# Fix Nextion Driver
		echo '[Unit]' > /lib/systemd/system/nextiondriver.service
		echo 'DefaultDependencies=no' >> /lib/systemd/system/nextiondriver.service
		echo 'Description=NextionDriver service' >> /lib/systemd/system/nextiondriver.service
		echo 'Before=timers.target mmdvmhost.service' >> /lib/systemd/system/nextiondriver.service
		echo 'After=local-fs.target wifi-country.service' >> /lib/systemd/system/nextiondriver.service
		echo '' >> /lib/systemd/system/nextiondriver.service
		echo '[Service]' >> /lib/systemd/system/nextiondriver.service
		echo 'User=root' >> /lib/systemd/system/nextiondriver.service
		echo 'WorkingDirectory=/usr/local/etc/' >> /lib/systemd/system/nextiondriver.service
		echo 'Type=forking' >> /lib/systemd/system/nextiondriver.service
		echo 'ExecStart=/usr/local/sbin/nextiondriver.service start' >> /lib/systemd/system/nextiondriver.service
		echo 'ExecStop=/usr/local/sbin/nextiondriver.service stop' >> /lib/systemd/system/nextiondriver.service
		echo 'ExecReload=/usr/local/sbin/nextiondriver.service reload' >> /lib/systemd/system/nextiondriver.service
		echo '' >> /lib/systemd/system/nextiondriver.service
		echo '[Install]' >> /lib/systemd/system/nextiondriver.service
		echo 'WantedBy=multi-user.target network-online.target' >> /lib/systemd/system/nextiondriver.service

		# Start the service
		systemctl daemon-reload
		systemctl enable --now nextiondriver.service

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.2.1..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.2.1)
		sed -i 's/4.2.1/4.2.2/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Remove the IPv6 Roadblocks
		rm -rf /etc/modprobe.d/ipv6.conf

		# Fix the ifnames in cmdline.txt
		grep -q "net.ifnames=0" /boot/cmdline.txt || sed -i 's/rootwait/net.ifnames=0 rootwait/' /boot/cmdline.txt

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.2.2..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.2.2)
		sed -i 's/4.2.2/4.2.3/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		CONF_FILE="/etc/nginx/sites-available/pi-star"
		if [ ! -f /etc/modprobe.d/ipv6.conf ] && ! grep -q 'listen \[::\]:80 default_server;' "$CONF_FILE" 2>/dev/null; then
			sed -i '/listen 80 default_server;/a\        listen [::]:80 default_server;' "$CONF_FILE"
		fi

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.2.3..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.2.3)
		#sed -i 's/4.2.3/4.2.4/g' /etc/pistar-release

		# Re-create the MOTD
		#/usr/local/sbin/pistar-motdgen

		# OK we are done
		#Message="[✓] Upgraded from ${pistarCurVersion} to 4.2.4..."
		Message="[✓] You are already running the latest version..."
		#echo $Message
		#exec "$0" "$@"
                #exit 1
	;;
	4.3.0)
		Message="[!] ERROR: Please re-image this system with Pi-Star v4.3.2 when released."
	;;
	4.3.1)
		Message="[!] ERROR: Please re-image this system with Pi-Star v4.3.2 when released."
	;;
	4.3.2)
		sed -i 's/4.3.2/4.3.3/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		# Create additional cmdline.txt file and link it
		cp /boot/firmware/cmdline.txt /boot/firmware/cmdline02w.txt
		(cd /boot && ln -s firmware/cmdline02w.txt ./)
		grep -q "brcmfmac.roamoff=1 brcmfmac.feature_disable=0x82000" /boot/firmware/cmdline02w.txt || sed -i 's/net.ifnames=0/brcmfmac.roamoff=1 brcmfmac.feature_disable=0x82000 net.ifnames=0/' /boot/firmware/cmdline02w.txt

		# Modify config.txt
		search_line="\[pi02\]"
		new_line="cmdline=cmdline02w.txt"
		if grep -q "\[pi02\]" /boot/firmware/config.txt; then
		    sed -i "/$search_line/a $new_line" /boot/firmware/config.txt
		fi

		# Modify /etc/rc.local
		search_line="sed -i 's/ firstboot//' /boot/firmware/cmdline.txt"
		new_line="sed -i 's/ firstboot//' /boot/firmware/cmdline02w.txt"
		search_line_escaped=$(echo "$search_line" | sed 's/[&/\]/\\&/g')
		if grep -q "$search_line" /etc/rc.local; then
		    if ! grep -q "$new_line" /etc/rc.local; then
		        sed -i "/$search_line_escaped/a \ \ \ \ \ \ \ \ $new_line" /etc/rc.local
		    fi
		fi

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.3.3..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.3.3)
		sed -i 's/4.3.3/4.3.4/g' /etc/pistar-release

		# Re-create the MOTD
		/usr/local/sbin/pistar-motdgen

		CONF_FILE="/etc/nginx/sites-available/pi-star"
		if [ ! -f /etc/modprobe.d/ipv6.conf ] && ! grep -q 'listen \[::\]:80 default_server;' "$CONF_FILE" 2>/dev/null; then
			sed -i '/listen 80 default_server;/a\        listen [::]:80 default_server;' "$CONF_FILE"
		fi

		# OK we are done
		Message="[✓] Upgraded from ${pistarCurVersion} to 4.3.4..."
		echo $Message
		exec "$0" "$@"
                exit 1
	;;
	4.3.4)
		#sed -i 's/4.3.4/4.3.5/g' /etc/pistar-release

		# Re-create the MOTD
		#/usr/local/sbin/pistar-motdgen

		# OK we are done
		#Message="[✓] Upgraded from ${pistarCurVersion} to 4.3.5..."
		Message="[✓] You are already running the latest version..."
		#echo $Message
		#exec "$0" "$@"
                #exit 1
	;;
	*)
		Message="[!] ERROR: Somthing went very wrong - I cant tell what version I am running"
	;;
	esac

	# OK We're done
	echo $Message

	# RPi 4/5 EEPROM upgrade checks
	if [[ "${pistarHardware}" == "RPi" ]] && dpkg --compare-versions "${pistarCurVersion}" ge "4.3.0"; then
		piBoardModel=$(tr -d '\0' < /proc/device-tree/model)
		if [[ "${piBoardModel}" == *"Raspberry Pi 4"* || "${piBoardModel}" == *"Raspberry Pi 5"* ]]; then
			# Pi 4 / 5 Detected, with a current OS
			echo "[INFO] Detected device: ${piBoardModel}"

			# Make sure the rpi-eeprom package is installed
			if ! command -v rpi-eeprom-update &> /dev/null; then
				echo "[INFO] rpi-eeprom-update not found. Installing..."
				apt update && sudo apt install -y rpi-eeprom
			fi

			# Run the EEPROM update check
			eepromUpdateStatus=$(rpi-eeprom-update)

			if echo "$UPDATE_STATUS" | grep -q "UPDATE AVAILABLE"; then
				echo "[!] RPi EEPROM update available! You should run: sudo rpi-eeprom-update -a && sudo reboot"
			else
				echo "[✓] RPi EEPROM is up to date."
			fi
		fi
	fi

	# All Complete
	echo "[✓] Upgrade process complete: syncing disk cache before making the disk Read-Only"

	# Make the disk read-only
	/bin/sync
	/bin/sync
	/bin/sync
	if [ -d /boot/firmware ]; then
		$(mount -o remount,ro / >/dev/null 2>&1 </dev/null ; mount -o remount,ro /boot/firmware >/dev/null 2>&1 </dev/null)
	else
		$(mount -o remount,ro / >/dev/null 2>&1 </dev/null ; mount -o remount,ro /boot >/dev/null 2>&1 </dev/null)
	fi
	echo "[INFO] Finished"
}

if [ -t 1 ]; then
	# run via terminal, only output to screen
	main_function
else
	# if not run via terminal, log everything into a log file
	if [ ! -d /var/log/pi-star ]; then
		mkdir -p /var/log/pi-star
	fi
	main_function >> /var/log/pi-star/pi-star_upgrade.log 2>&1
fi

exit 0
